package com.terrace.core.spring.converter;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.convert.converter.Converter;

/**
 * 自定义String转java.utils.Date转换器 
 * 					支持如下格式：yyyyMMdd、yyyy-MM-dd、yyyyMMddHHmmss、yyyy-MM-dd
 * HH:mm:ss
 * 
 * @author jiangyg
 *
 */
public class String2DateConverter implements Converter<String, Date>, InitializingBean {

	private static final Logger logger = LoggerFactory.getLogger(String2DateConverter.class);
	
	/**
	 * 支持的转换格式
	 */
	private static final String[] FORMATS = new String[] { "yyyyMMdd", "yyyy-MM-dd", "yyyyMMddHHmmss",
			"yyyy-MM-dd HH:mm:ss" };
	
	private SimpleDateFormat dateFormat1 = new SimpleDateFormat(FORMATS[0]);

	private SimpleDateFormat dateFormat2 = new SimpleDateFormat(FORMATS[1]);

	private SimpleDateFormat dateFormat3 = new SimpleDateFormat(FORMATS[2]);

	private SimpleDateFormat dateFormat4 = new SimpleDateFormat(FORMATS[3]);

	@Override
	public Date convert(String source) {
		if (StringUtils.isBlank(source)) {
			return null;
		}
		try {
			int length = StringUtils.length(source);
			if (length == 8) {
				return dateFormat1.parse(source);
			}
			if (length == 10) {
				return dateFormat2.parse(source);
			}
			if (length == 14) {
				return dateFormat3.parse(source);
			}
			if (length == 19) {
				return dateFormat4.parse(source);
			}
			logger.warn("String转java.utils.Date转换器警告：仅支持格式" + FORMATS + ",不支持字符串[" + source + "]的转换");
		} catch (Exception ex) {
			logger.error("自定义String转java.utils.Date转换器执行出错：", ex);
		}
		return null;
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		dateFormat1.setLenient(false);
		dateFormat2.setLenient(false);
		dateFormat3.setLenient(false);
		dateFormat4.setLenient(false);
		logger.info("装配自定义数据转换器：String转java.utils.Date转换器装载成功……");
	}

}
